"""
频率控制器
用于控制请求频率，避免被封禁
"""
import time
import random
import logging
from typing import Optional
from spider.config.settings import (
    MIN_REQUEST_INTERVAL,
    MAX_REQUEST_INTERVAL,
    RANDOM_INTERVAL,
)

logger = logging.getLogger(__name__)


class RateLimiter:
    """请求频率限制器"""
    
    def __init__(
        self,
        min_interval: float = MIN_REQUEST_INTERVAL,
        max_interval: float = MAX_REQUEST_INTERVAL,
        random_interval: bool = RANDOM_INTERVAL,
    ):
        self.min_interval = min_interval
        self.max_interval = max_interval
        self.random_interval = random_interval
        self.last_request_time = 0.0
    
    def wait(self):
        """等待直到可以发送下一个请求"""
        current_time = time.time()
        elapsed = current_time - self.last_request_time
        
        if self.random_interval:
            interval = random.uniform(self.min_interval, self.max_interval)
        else:
            interval = self.min_interval
        
        if elapsed < interval:
            wait_time = interval - elapsed
            logger.debug(f"Rate limiter: waiting {wait_time:.2f} seconds")
            time.sleep(wait_time)
        
        self.last_request_time = time.time()
    
    def reset(self):
        """重置最后请求时间"""
        self.last_request_time = 0.0

